package com.hmdp.ThreadUtil.pc;/**
 * @Author:fengxiaohui
 * @Description:
 * @Date:Create in 2:52 下午 2023/6/7
 * @Modified By:
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *@Author:fengxiaohui
 *@Description:
 线程 操作 资源类
 本题实现：线程A执行完业务，线程B执行，最后线程C执行
 */
public class Task3 {

    public static void main(String[] args) {
        Date3 date = new Date3();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                date.printA();
            }

        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                date.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                date.printC();
            }
        },"C").start();
    }


}

class Date3{
    private int number = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1  = lock.newCondition();
    private Condition condition2  = lock.newCondition();
    private Condition condition3  = lock.newCondition();
    public void printA(){
        //判断、干活、通知
        lock.lock();
        try {
            while (number != 1){
                condition1.await();
            }
            number = 2;
            System.out.println(Thread.currentThread().getName() + "====>执行");
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB(){
        //判断、干活、通知
        lock.lock();
        try {

            while (number != 2){
                condition2.await();
            }
            number = 3;
            System.out.println(Thread.currentThread().getName() + "====>执行");
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC(){
        //判断、干活、通知
        lock.lock();
        try {

            while (number != 3){
                condition3.await();
            }
            number = 1;
            System.out.println(Thread.currentThread().getName() + "====>执行");
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}


